<template>
  <el-dialog
    title="分配权限"
    :visible="dialogVisible"
    @close="handleClose"
  >
    <el-tree
      ref="permTree"
      :data="permData"
      show-checkbox
      default-expand-all
      :props="defaultProps"
      check-strictly
      node-key="id"
      :default-checked-keys="permIds"
    />
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="handleComfirm">确定</el-button>
        <el-button size="small" @click="handleClose">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { assignPermApi, getPermissionListApi, getRoleDetailApi } from '@/api/permisson'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'HrsaasManagerPermission',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      permData: [], // 权限列表
      defaultProps: {
        label: 'name'
      },
      permIds: [] // 当前角色的权限列表
    }
  },
  watch: {
    async dialogVisible(val) {
      // 弹窗打开的时候去调用
      if (val) {
        await this.getPermissionList()
        await this.getRoleDetail()
      }
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:dialogVisible', false)
    },
    // 获取权限列表
    async getPermissionList() {
      const data = await getPermissionListApi()
      this.permData = tranListToTreeData(data, '0')
    },
    // 获取当前角色拥有的权限
    async getRoleDetail() {
      const { permIds } = await getRoleDetailApi(this.$attrs['row-id'])
      this.permIds = permIds
    },
    // 点击确定分配权限
    async handleComfirm() {
      // console.log(this.$refs.permTree.getCheckedKeys())
      await assignPermApi({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.$attrs['row-id'] })
      this.$message.success('角色分配成功')
      this.handleClose()
    }

  }
}
</script>
